<script lang="ts" setup>
  import * as echarts from 'echarts';
  import {onActivated, onMounted, onUnmounted, reactive, ref, watch} from 'vue';
  import stomp from "@/variable/Stomp";
  import {regionTree} from "@/api/site";
  import getThemeConfig from "@/variable/echarts";

  const props = defineProps<{
    id: string
  }>()

  let myChart: any
  let option = getThemeConfig()

  const sensor = ref('')

  const initEcharts = () => {
    const chartDom = document.getElementById('feature-panel')
    if (chartDom == null) {
      return
    }
    chartDom.removeAttribute('_echarts_instance_')
    myChart = echarts.init(chartDom);
    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize)
  }
  //存储特征值的数组
  let seriesData = []
  const initSeriesData = () => {
    seriesData = []
    TYPES.forEach(() => {
      seriesData.push([])
    })
  }
  const loadData = () => {
    let oldAccess: number
    stomp.subscribe('/topic/fd', (message) => {

      if (message.id !== conditionForm.station) {
        return
      }
      if (!oldAccess || (oldAccess && oldAccess != conditionForm.access)) {
        initSeriesData()
      }
      message.pcList.forEach((pc, index) => {
        if (index + 1 == conditionForm.access) {
          TYPES.forEach((type, idx) => {
            seriesData[idx].push([message.timestamp * 1000, pc[type] * 1000])
            if (seriesData[idx].length > conditionForm.timeRange) {
              seriesData[idx].splice(0, seriesData[idx].length - conditionForm.timeRange)
            }
          })
        }
      })

      const series = []
      seriesData.forEach((data, idx) => {
        series.push({
          data: data,
          name: LABELS[idx],
          type: 'line',
          smooth: true,
          symbol: 'none'
        })
      })
      myChart.setOption({
        series,
        legend: {
          data: LABELS,
          left: '20%'
        }
      });
      oldAccess = conditionForm.access
    });
  }

  // const TYPES = ["max1s", "min1s", "max5s", "min5s", "max30s", "min30s", "avg3s", "avg60s"]
  // const LABELS = ["1s最大值", "1s最小值", "5s最大值", "5s最小值", "30s最大值", "30s最小值", "3s平均值", "60s绝对均值"]

  const TYPES = ["max1s", "min1s"]
  const LABELS = ["1s最大值", "1s最小值"]

  onMounted(() => {
    initStation().then(() => {
      initEcharts()
      initSeriesData()
      loadData()
    })
  })

  onUnmounted(() => {
    window.removeEventListener("resize", myChart?.resize)
  })
  onActivated(() => {
    initEcharts()
  })
  const timeRanges = [
    {
      value: 30,
      label: '30秒'
    },
    {
      value: 40,
      label: '40秒'
    },
    {
      value: 60,
      label: '60秒'
    },
    {
      value: 80,
      label: '80秒'
    },
    {
      value: 120,
      label: '120秒'
    },
    {
      value: 150,
      label: '150秒'
    },
  ]

  const accesses = [
    {
      value: 1,
      label: '主E-W'
    },
    {
      value: 2,
      label: '主N-S'
    },
    {
      value: 3,
      label: '主U-D'
    },
    {
      value: 4,
      label: '备E-W'
    },
    {
      value: 5,
      label: '备N-S'
    },
    {
      value: 6,
      label: '备U-D'
    }
  ]
  const conditionForm = reactive({
    access: 1,
    timeRange: 30,
    station: ''
  })

  const stations = ref([])
  const initStation = () => {
    return new Promise((resolve) => {
      regionTree().then(res => {
        stations.value = res.data.map((region: {
          code: any; name: any; stationInfoList: any[]; regions: any[]
        }) => {
          let regions = region.regions;
          let regionItem = {
            value: region.code,
            label: region.name,
            children: []
          }
          if (!regions){
            return regionItem;
          }
          for (let region1 of regions) {
            regionItem.children.push({
              value: region1.code,
              label: region1.name,
              children: region1.stationInfoList.map(station => {
                if (!props.id && station.online) {
                  conditionForm.station = station.id
                }
                const sta = {
                  value: station.id,
                  label: station.id,
                  children: [],
                  disabled: station.online != 1
                }
                return sta
              })
            })
          }

          return regionItem
        })
        resolve(stations.value)
      })
    })
  }
  watch(
    () => props.id,
    (newVal) => {
      conditionForm.station = newVal
      initSeriesData()
    },
    {
      immediate: true
    }
  )
</script>
<template>
  <div class="panel-wrap">
    <div class="condition">
      <el-form :inline="true" :model="conditionForm" class="con-form" size="default">
        <el-form-item label="站点">
          <el-tree-select v-model="conditionForm.station" :data="stations" placeholder="请选择站点" style="width:180px;"/>
        </el-form-item>
        <el-form-item label="时长">
          <el-select v-model="conditionForm.timeRange" placeholder="请选择时长" style="width:80px;">
            <el-option
              v-for="item in timeRanges"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="传感器">-->
        <!--          <el-switch-->
        <!--            v-model="sensor"-->
        <!--            size="default"-->
        <!--            inline-prompt-->
        <!--            color="#3aecff"-->
        <!--            active-text="主传感器"-->
        <!--            inactive-text="备传感器"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="通道">
          <el-select v-model="conditionForm.access" placeholder="请选择通道" style="width:100px;">
            <el-option
              v-for="item in accesses"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div id="feature-panel"></div>
  </div>
</template>
<style scoped lang="scss">

  .panel-wrap {
    padding: 20px 5px;
    height: 100%;
    width: 100%;

    .condition {

      .con-form {

      }
    }

    #feature-panel {
      width: 100%;
      height: calc(100% - 80px);
    }
  }

  .el-switch {
    --el-switch-on-color: #16c8db;
    --el-switch-off-color: #7da6aa;
  }
</style>
